package com.red.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.red.entity.User;
import com.red.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;

public class UserQueryServlet extends HttpServlet {
    private static final String OPTIONS_COOKIE = "options";
    private static final String LEN = "len";
    private static final String CUR_PAGE = "page";
    private static final String PAGES = "pages";
    private static final String USER_NORMAL = "user_normal";
    private static final String USER_MEMBER = "user_member";
    private static final String USER_VIP = "user_vip";
    private static final String USER_ADMIN = "user_admin";

    private JSONObject jsonDefaults;

    {
        jsonDefaults = new JSONObject();
        jsonDefaults.put(CUR_PAGE, 1);
        jsonDefaults.put(LEN, 10);
        jsonDefaults.put(USER_NORMAL, "on");
        jsonDefaults.put(USER_MEMBER, "");
        jsonDefaults.put(USER_VIP, "");
        jsonDefaults.put(USER_ADMIN, "");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

        Cookie[] cookies = req.getCookies();
        Cookie optionsCookie = null;

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(OPTIONS_COOKIE)) {
                optionsCookie = cookie;
                break;
            }
        }

        if (optionsCookie != null) {
            jsonDefaults = JSONObject.parseObject(URLDecoder.decode(optionsCookie.getValue(), "utf-8"));
            System.out.println(jsonDefaults.toString());

            if (req.getAttribute("deleteResult") == null &&
                    req.getAttribute("updateResult") == null &&
                    req.getAttribute("addResult") == null) {
                // 参数更新
                if (req.getParameter(CUR_PAGE) != null) {
                    updateJSON(CUR_PAGE, req.getParameter(CUR_PAGE));
                } else {
                    jsonDefaults.put(CUR_PAGE, 1);
                    updateJSON(LEN, req.getParameter(LEN), 10);
                    updateCheckbox(USER_NORMAL, req.getParameter(USER_NORMAL));
                    updateCheckbox(USER_MEMBER, req.getParameter(USER_MEMBER));
                    updateCheckbox(USER_VIP, req.getParameter(USER_VIP));
                    updateCheckbox(USER_ADMIN, req.getParameter(USER_ADMIN));
                }
            }
            // 老版本失效
            optionsCookie.setMaxAge(0);
            resp.addCookie(optionsCookie);
        }

        Cookie newCookie = new Cookie(OPTIONS_COOKIE, URLEncoder.encode(jsonDefaults.toJSONString(), "utf-8"));
        newCookie.setMaxAge(60 * 10);
        resp.addCookie(newCookie);

        int len = jsonDefaults.getInteger(LEN);
        int curPage = jsonDefaults.getInteger(CUR_PAGE);
        User[] usersList = new UserServiceImpl().selectAllUser(curPage, len, getUserType());

        req.setAttribute("len", len);
        req.setAttribute("curPage", curPage);
        req.setAttribute("userList", usersList);
        req.setAttribute(PAGES, (int) Math.ceil((double) new UserServiceImpl().getPages(getUserType()) / len));

        req.setAttribute(USER_NORMAL, jsonDefaults.getString(USER_NORMAL));
        req.setAttribute(USER_MEMBER, jsonDefaults.getString(USER_MEMBER));
        req.setAttribute(USER_VIP, jsonDefaults.getString(USER_VIP));
        req.setAttribute(USER_ADMIN, jsonDefaults.getString(USER_ADMIN));

        req.getRequestDispatcher("jsp/manage/user.jsp").forward(req, resp);
    }

    private boolean updateJSON(String param, Object value) {
        if (value != null) {
            jsonDefaults.put(param, value);
            return true;
        }
        return false;
    }
    private void updateJSON(String param, Object value, Object empty) {
        if(!updateJSON(param,value))updateJSON(param,empty);
    }

    private void updateCheckbox(String param, Object value) {
        // 当没有收到 checkbox 的参数
        if (!updateJSON(param, value)) {
            // 当 cookie 中的 checkbox 处于 on 状态，就更新为关闭状态
            if (jsonDefaults.getString(param).equals("on")) {
                jsonDefaults.put(param, "");
            }
        }
    }

    private ArrayList<Integer> getUserType() {
        ArrayList<Integer> types = new ArrayList<>();
        if (!jsonDefaults.getString(USER_NORMAL).isEmpty()) types.add(0);
        if (!jsonDefaults.getString(USER_MEMBER).isEmpty()) types.add(1);
        if (!jsonDefaults.getString(USER_VIP).isEmpty()) types.add(2);
        if (!jsonDefaults.getString(USER_ADMIN).isEmpty()) types.add(3);
        return types;
    }
}
